package com.example.questionnaire.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.questionnaire.dao.AppidAndSecretMapper;
import com.example.questionnaire.pojo.DO.AppidAndSecret;
import com.example.questionnaire.service.AppidAndSecretService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class AppidAndSecretServiceImpl implements AppidAndSecretService {
    @Autowired
    AppidAndSecretMapper appidAndSecretMapper;


    @Override
    public boolean tokenTimeout(String token) {
        try {
            Date expirationDate = this.loadTokenExpiration(token);
            Date date = new Date(System.currentTimeMillis());
            int i =date.compareTo(expirationDate);
            int b = 0;
            return i > b;
        }catch (Exception e){
            e.printStackTrace();
            return true;
        }
    }

    private Date loadTokenExpiration(String token){
        QueryWrapper<AppidAndSecret> wrapper = new QueryWrapper<>();
        wrapper.select("appid","secret");
        AppidAndSecret appidAndSecret = appidAndSecretMapper.selectOne(wrapper);

        String secret = appidAndSecret.getSecret();
        Jws<Claims> claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token);
        claims.getBody().getExpiration();
        return claims.getBody().getExpiration();
    }
}
